<template>
    <div class="comment-body">

        <h2>评论区</h2>

        <div class="comment-sub">
            <img :src="user.avatar ? user.avatar : avatar_default" class="avatar">
            <textarea class="comment-input" v-model="commentInput" name="" id="" cols="30" rows="10"
                placeholder="请输入评论"></textarea>
            <el-button color="#78e26c" class="comment-sub-btn" @click="submitComment">发布</el-button>
        </div>
        <div class="comment-container" v-if="showComment && showHotComment" v-loading="loading"
            element-loading-text="Loading..." element-loading-background="rgb(255,255,255,0.95)">

            <h3>最热评论</h3>

            <div class="comment-box" v-for="(item, index) in hotCommentArr" :key="index">
                <img :src="item.profilePath" class="avatar" />
                <div class="comment-box-right">
                    <div class="user-info">
                        <p class="user-name">{{ item.nickName }}</p>
                        <PersonalType :role="item.roleId" />
                    </div>
                    <p class="comment">{{ item.content }}</p>
                    <div class="comment-detail">
                        <div class="time">
                            {{ item.publishTime }}
                        </div>
                        <div class="like-box" @click="item.likeNum++;">
                            <img src="../../assets/icons/Like.svg" alt="">
                            <span>{{ item.likeNum }}</span>
                        </div>

                        <div class="reply-bt" @click="showReply(item.commentId, item.userId, item.nickName)">回复<span
                                v-show="item.replyNum !== 0">({{ item.replyNum }})</span></div>
                    </div>

                </div>


            </div>
        </div>
        <div class="comment-container" v-if="showComment" v-loading="loading" element-loading-text="Loading..."
            element-loading-background="rgb(255,255,255,0.95)">

            <h3>最新评论</h3>

            <div class="comment-box" v-for="(item, index) in latestCommentArr" :key="index">
                <img :src="item.profilePath" class="avatar" />
                <div class="comment-box-right">
                    <div class="user-info">
                        <p class="user-name">{{ item.nickName }}</p>
                        <PersonalType :role="item.roleId" />

                    </div>
                    <p class="comment">{{ item.content }}</p>
                    <div class="comment-detail">
                        <div class="time">
                            {{ item.publishTime }}
                        </div>
                        <div class="like-box" @click="item.likeNum++;">
                            <img src="../../assets/icons/Like.svg" alt="">

                            <span>{{ item.likeNum }}</span>
                        </div>

                        <div class="reply-bt" @click="showReply(item.commentId, item.userId, item.nickName)">回复<span
                                v-show="item.replyNum !== 0">({{ item.replyNum }})</span></div>
                    </div>

                </div>
            </div>
        </div>
        <div class="no-comment" v-if="!showComment" v-loading="loading" element-loading-text="Loading..."
            element-loading-background="rgb(255,255,255,0.95)">
            <p>暂无评论，快抢沙发吧~</p>
        </div>
        <CommentReply ref="replyComponent" />
    </div>
</template>
<script setup>
import avatar_default from "@/assets/icons/avatar.png";
import { onMounted, ref } from "vue";
import CommentReply from "./CommentReply.vue";
import { ElMessage } from "element-plus";
import PersonalType from "../PersonalType.vue";
import { GetComment, PostComment, GetNextComment } from "@/api/front/contest";
import store from "@/store";

const loading = ref(true);
const props = defineProps({
    replyContent: {
        type: Number,
        default: 0,
    },
    replyId: {
        type: Number,
        default: 0,
    }
});

const user = store.state.userInfo;
store.commit("setCommentProperty", { key: "userId", value: user.userId });
store.commit("setCommentProperty", { key: "replyContent", value: props.replyContent });
store.commit("setCommentProperty", { key: "replyId", value: props.replyId });

const commentInput = ref("");
const comment = ref("");
const showComment = ref(false);
const showHotComment = ref(false);
const hotCommentArr = ref([])
const latestCommentArr = ref([])

const replyComponent = ref(null);


const showReply = (id, userId, name) => {
    replyComponent.value.showReply(id, userId, name);
};

// 给hotCommentArr的每个对象添加一个replyNum属性,赋值为0
const addReplyNum = (arr) => {
    arr.forEach(async (item) => {
        const res = await GetNextComment({
            topId: item.commentId,
            page_num: 1,
            page_size: 999,
        })
        item.replyNum = res.data.total;
    });
};


const submitComment = async () => {
    if (user.userId == 0) {
        ElMessage({
            message: "请先登录",
            type: "error"
        });
        return;
    }
    if (commentInput.value === "") {
        ElMessage({
            message: "评论不能为空",
            type: "error"
        });
        return;
    }
    store.commit("setCommentProperty", { key: "content", value: commentInput.value });
    const data = store.state.comment
    console.log("comment-vuex", store.state.comment)
    const res = await PostComment(data);
    if (res.data == "添加成功") {
        ElMessage({
            message: "评论成功",
            type: "success"
        });
        commentInput.value = ''
        getComment()
    } else {
        ElMessage({
            message: "评论失败",
            type: "error",
        });
    }
};


//  一个函数根据comment的likeNum值大小选出前5的热门评论
const getHotComment = (commentList) => {
    const sortedComments = [...commentList].sort((a, b) => b.likeNum - a.likeNum);
    const hotComments = sortedComments.slice(0, 3);
    return hotComments;
}

const pageNum = ref(1)
const pageSize = ref(999)
const totalComment = ref(0)
const data2 = {
    replyContent: props.replyContent,
    replyId: props.replyId,
    page_num: pageNum.value,
    page_size: pageSize.value
}

const getComment = async () => {
    const res = await GetComment(data2)
    // console.log("comment", res)
    const resData = res.data
    pageNum.value = resData.pageNum
    comment.value = resData.pageList
    totalComment.value = resData.total
    loading.value = false
    if (totalComment.value == 0) {
        return
    }
    showComment.value = true
    latestCommentArr.value = comment.value
    addReplyNum(latestCommentArr.value)
    if (totalComment.value > 5) {
        hotCommentArr.value = getHotComment(comment.value)
        console.log("hotCommentArr", hotCommentArr.value)
        showHotComment.value = true
        addReplyNum(hotCommentArr.value)
    }

}

onMounted(async () => {
    getComment()
});

</script>
<style lang="scss" scoped>
.comment-body {

    .avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }


    .comment-sub {
        display: flex;
        align-items: center;

        .avatar {

            border-radius: 50%;
            margin: 0 10px;
        }

        .comment-input {
            width: 100%;
            height: 60px;
            border: 1px solid #ccc;
            border-radius: 10px;
            margin: 10px 0;
            outline: none;
            resize: none;
            padding: 10px;
            color: #666;
            font-weight: bold;
            box-sizing: border-box;

            &::placeholder {
                color: #999;
            }

            &:focus {
                border: 2px solid #42b983;
            }
        }

        .comment-sub-btn {
            width: 100px;
            height: 40px;
            margin-left: 10px;
            font-weight: bold;
            color: white;
            border-radius: 10px;
            transition: all 0.2s ease-in-out;

            &:hover {
                cursor: pointer;
                color: #2c3e50;
                box-shadow: 0 0 4px #afafaf;
            }
        }
    }

    .comment-container {
        h3 {
            margin: 10px 0;
        }

        .comment-box {
            display: flex;

            .avatar {
                margin: 0px 20px;
            }

            .comment-box-right {

                .user-info {
                    display: flex;
                    flex-direction: column;
                    height: 60px;
                    justify-content: space-around;

                    .user-name {
                        padding: 0 5px;
                    }

                    .user-type {
                        background-color: #ccc;
                        border-radius: 10px;
                        padding: 0 5px;
                        width: fit-content;
                    }
                }

                .comment {
                    margin: 10px 0px;
                }

                .comment-detail {
                    display: flex;
                    margin: 10px 0px;

                    .time {
                        margin-right: 20px;
                    }

                    .like-box {
                        display: flex;
                        align-items: center;
                        margin-right: 20px;
                        cursor: pointer;

                        img {
                            width: 20px;
                            height: 20px;
                        }

                        // span {}
                    }

                    .reply-bt {

                        cursor: pointer;

                        &:hover {
                            color: #42b983;
                        }

                        span {
                            margin-left: 5px;
                            font-size: 14px;
                        }
                    }
                }


            }

        }
    }

    .no-comment {
        text-align: center;
        margin: 20px 0;
    }


}</style>